package com.haredot.controller;

import com.haredot.entity.Position;
import com.haredot.service.PositionService;
import com.haredot.utils.ValidUtils;
import com.haredot.vo.PageVo;
import com.haredot.vo.R;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/position")
public class PositionController {

    @Resource
    private PositionService positionService ;

    @GetMapping("/list")
    @PreAuthorize("hasAnyAuthority('position', 'position:query')")
    public R<PageVo> list(@RequestParam(value = "page", defaultValue = "1", required = false) Integer page,
                          @RequestParam(value = "rows", required = false, defaultValue = "10") Integer rows,
                          @RequestParam(value = "name", required = false) String name,
                          @RequestParam(value = "state", required = false) Boolean state) {

        PageVo pageVo = new PageVo(page, rows) ;

        Map<String, Object> params = new HashMap<>();
        params.put("name", name);
        params.put("state", state) ;

        return positionService.queryPositionsByPage(pageVo, params);
    }

    @PostMapping("/add")
    @PreAuthorize("hasAuthority('position:add')")
    public R<?> addPosition(@Validated @RequestBody Position position, BindingResult bindingResult) {
        return ValidUtils.toResult(bindingResult, ()-> positionService.savePosition(position));
    }

    @PutMapping("/update/{id}")
    @PreAuthorize("hasAuthority('position:update')")
    public R<?> addPosition(@PathVariable("id") Long id,
                            @Validated @RequestBody Position position, BindingResult bindingResult) {
        position.setId(id);
        return ValidUtils.toResult(bindingResult, ()-> positionService.updatePosition(position));
    }

    @DeleteMapping("/del/{id}")
    @PreAuthorize("hasAuthority('position:delete')")
    public R<?> deletePosition(@PathVariable("id") Long id) {
        return positionService.removePosition(id);
    }

    @DeleteMapping("/batchDel")
    @PreAuthorize("hasAuthority('position:batch:remove')")
    public R<?> deletePosition(@RequestBody List<Long> ids, BindingResult bindingResult) {
        if (ids.isEmpty()) {
            return R.fail("参数校验错误").data(Map.of("funcIds", "请至少选择一个需要删除的职务"));
        }
        return positionService.removeBatchPosition(ids);
    }

}
